<template>
  <div class="preview-container">

    <!-- 预览内容 -->
    <div class="preview-content" ref="previewContent">
      <div class="preview-document">
        <!-- 封面 -->
        <div class="cover-page">
          <div class="cover-content">
            <h1 class="cover-title">{{ paperName || '白皮书' }}</h1>
            <div class="cover-meta">
            </div>
          </div>
        </div>

        <!-- 目录 -->
        <div class="toc-page" v-if="chapters.length > 0">
          <h2 class="toc-title">目录</h2>
          <div class="toc-content">
            <div 
              v-for="(chapter, index) in chapters" 
              :key="'toc-' + index" 
              class="toc-item"
            >
              <span class="toc-chapter">{{ index + 1 }}. {{ chapter.chapterName }}</span>
              <span class="toc-page-number">{{ getChapterPageNumber(index) }}</span>
            </div>
          </div>
        </div>

        <!-- 正文内容 -->
        <div class="content-pages">
          <div 
            v-for="(chapter, chapterIndex) in chapters" 
            :key="'chapter-' + chapterIndex" 
            class="chapter-page"
          >
            <div class="chapter-header">
              <h2 class="chapter-title">
                {{ chapterIndex + 1 }}. {{ chapter.chapterName || '未命名章节' }}
              </h2>
            </div>
            
            <div class="chapter-content">
              <div 
                v-for="(title, titleIndex) in chapter.contentTitles" 
                :key="'title-' + titleIndex" 
                class="title-section"
              >
                <h3 class="section-title">
                  {{ chapterIndex + 1 }}.{{ titleIndex + 1 }} {{ title.title || '未命名标题' }}
                </h3>
                 
                <div 
                  class="section-content" 
                  v-if="title.fianlAnalyseResult || title.aiAnalyseResult"
                  v-html="formatPreviewContent(title.fianlAnalyseResult || title.aiAnalyseResult)"
                ></div>
                <div v-else class="empty-content">
                  <p>暂无内容</p>
                </div>

                <!-- 子标题内容 -->
                <div 
                  v-for="(subTitle, subIndex) in title.subTitles" 
                  :key="'sub-' + subIndex" 
                  class="subtitle-section"
                >
                  <h4 class="subtitle-title">
                    {{ chapterIndex + 1 }}.{{ titleIndex + 1 }}.{{ subIndex + 1 }} {{ subTitle.label || '未命名子标题' }}
                  </h4>
                  
                  <div 
                    class="subtitle-content" 
                    v-if="subTitle.finalContent || subTitle.content"
                    v-html="formatPreviewContent(subTitle.finalContent || subTitle.content)"
                  ></div>
                  <div v-else class="empty-content">
                    <p>暂无内容</p>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 结束页 -->
        <div class="end-page">
          <div class="end-content">
            <p>—— 完 ——</p>
            <p class="end-meta">文档生成于 {{ generateTime }}</p>
          </div>
        </div>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-overlay">
      <el-loading-spinner class="el-icon-loading" style="font-size: 32px; color: #1E60FA;"></el-loading-spinner>
      <p>正在加载预览内容...</p>
    </div>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import axios from "axios";

export default {
  name: "WhitepaperPreview",
  data() {
    return {
      paperName: '',
      projectId: 0,
      chapters: [],
      projectInfo: {},
      generateTime: '',
      loading: false
    };
  },
  mounted() {
    this.projectId = this.parseProjectIdFromUrl();
    if (!this.projectId) {
      this.$message.error("未获取到有效项目ID");
      return;
    }
    this.loadPreviewData();
  },
  methods: {
    parseProjectIdFromUrl() {
      try {
        const urlParams = new URLSearchParams(window.location.search);
        const queryId = Number(urlParams.get('id'));
        return Number.isInteger(queryId) && queryId > 0 ? queryId : 0;
      } catch (err) {
        return 0;
      }
    },

    async loadPreviewData() {
      this.loading = true;
      try {
        await Promise.all([
          this.getProjectDetail(),
          this.getOutlineData()
        ]);
        this.generateTime = new Date().toLocaleString('zh-CN');
      } catch (error) {
        this.$message.error('加载预览数据失败');
        console.error('加载预览数据失败:', error);
      } finally {
        this.loading = false;
      }
    },

    async getProjectDetail() {
      try {
        const res = await axios.get(
          `${process.env.VUE_APP_BASE_API}/system/project/${this.projectId}`,
          { headers: { Authorization: "Bearer " + getToken() } }
        );
        const { code, data } = res.data || {};
        if (code === 200 && data) {
          this.paperName = data.paperName || data.whitePaperName || data.name || '';
          this.projectInfo = {
            orgName: data.orgName || '',
            industry: data.industry || '',
            briefIntroduction: data.briefIntroduction || ''
          };
        }
      } catch (error) {
        console.error('Failed to load project details:', error);
      }
    },

    async getOutlineData() {
      try {
        const res = await axios.get(
          `${process.env.VUE_APP_BASE_API}/system/outline/list`,
          { 
            params: { projectId: this.projectId }, 
            headers: { Authorization: "Bearer " + getToken() } 
          }
        );
        const { code, data } = res.data || {};
        if (code === 200 && Array.isArray(data)) {
          this.processOutlineData(data);
        } else {
          this.chapters = [];
        }
      } catch (error) {
        console.error('Failed to load outline data:', error);
        this.chapters = [];
      }
    },

    processOutlineData(data) {
      this.chapters = data.map(level1 => {
        const level2List = level1.children || [];
        const contentTitles = level2List.map(level2 => {
          const level3List = level2.children || [];
          const subTitles = level3List.map(level3 => ({
            id: level3.id,
            label: level3.label || '未命名子标题',
            summary: level3.summary || '',
            createTime: level3.createTime || '',
            content: level3.content || '',
            finalContent: level3.finalContent || ''
          }));

          const firstLevel3 = level3List[0] || {};
          return {
            id: level2.id,
            title: level2.label || '未命名标题',
            dataSource: firstLevel3.summary || '',
            createTime: firstLevel3.createTime || '',
            aiAnalyseResult: firstLevel3.finalContent || firstLevel3.content || '',
            fianlAnalyseResult: firstLevel3.finalContent || firstLevel3.content || '',
            subTitles: subTitles
          };
        });

        return {
          chapterName: level1.label || '未命名章节',
          contentTitles: contentTitles,
          isExpanded: true
        };
      });
    },

    formatPreviewContent(content) {
      if (!content) return '<p>暂无内容</p>';
      
      // 解码URL编码的内容
      try {
        content = decodeURIComponent(content);
      } catch (e) {
        console.log('Content is not URL encoded');
      }
      
      // 确保内容是HTML格式
      if (!content.includes('<')) {
        content = content.split('\n').map(line => {
          if (line.trim() === '') return '<br>';
          return `<p>${line}</p>`;
        }).join('');
      }
      
      return content;
    },

    getChapterPageNumber(chapterIndex) {
      return 2 + chapterIndex * 2 + 1;
    },

    goBack() {
      window.history.back();
    },

    printPreview() {
      window.print();
    },

    exportPDF() {
      this.$message.info('...');
    }
  }
};
</script>

<style scoped>
.preview-container {
  min-height: 100vh;
}

.preview-header {
  background: white;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.header-content {
  max-width: 1200px;
  margin: 0 auto;
}

.preview-title-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.preview-title {
  color: #0C1124;
  margin: 0;
  font-size: 24px;
}

.preview-actions {
  display: flex;
  gap: 10px;
}

.preview-content {
  background: white;
  border-radius: 8px;
  padding: 40px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  max-width: 1200px;
  margin: 0 auto;
}

/* 预览文档样式 */
.preview-document {
  font-family: 'SimSun', '宋体', serif;
  line-height: 1.8;
  color: #333;
}

/* 封面样式 */
.cover-page {
  height: 80vh;
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
  border-bottom: 2px solid #e6e6e6;
  margin-bottom: 40px;
}

.cover-title {
  font-size: 36px;
  color: #0C1124;
  margin-bottom: 20px;
}

.cover-meta {
  color: #666;
  font-size: 16px;
}

/* 目录样式 */
.toc-page {
  margin-bottom: 40px;
  border-bottom: 2px solid #e6e6e6;
  padding-bottom: 40px;
}

.toc-title {
  text-align: center;
  font-size: 24px;
  margin-bottom: 30px;
  color: #0C1124;
}

.toc-content {
  max-width: 600px;
  margin: 0 auto;
}

.toc-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 12px;
  padding: 8px 0;
  border-bottom: 1px dashed #e6e6e6;
}

.toc-chapter {
  color: #333;
}

.toc-page-number {
  color: #666;
}

/* 章节样式 */
.chapter-page {
  margin-bottom: 60px;
  page-break-inside: avoid;
}

.chapter-header {
  border-bottom: 2px solid #1E60FA;
  padding-bottom: 15px;
  margin-bottom: 30px;
}

.chapter-title {
  color: #0C1124;
  font-size: 24px;
  margin: 0;
}

/* 标题区域样式 */
.title-section {
  margin-bottom: 40px;
}

.section-title {
  color: #1E60FA;
  font-size: 20px;
  margin-bottom: 20px;
  border-left: 4px solid #1E60FA;
  padding-left: 15px;
}

.section-content {
  margin-bottom: 20px;
}

/* 子标题样式 */
.subtitle-section {
  margin: 25px 0;
  padding-left: 20px;
}

.subtitle-title {
  color: #333;
  font-size: 16px;
  margin-bottom: 15px;
  font-weight: 600;
}

.subtitle-content {
  color: #555;
}

/* 空内容样式 */
.empty-content {
  color: #999;
  font-style: italic;
  text-align: center;
  padding: 20px;
  background: #f9f9f9;
  border-radius: 4px;
}

/* 结束页样式 */
.end-page {
  text-align: center;
  padding: 60px 0;
  color: #666;
  border-top: 1px solid #e6e6e6;
  margin-top: 40px;
}

.end-meta {
  margin-top: 20px;
  font-size: 14px;
}

/* 加载状态 */
.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.9);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  z-index: 9999;
}

/* 打印样式 */
@media print {
  .preview-header,
  .preview-actions,
  .back-btn {
    display: none !important;
  }
  
  .preview-container {
    padding: 0;
    background: white;
  }
  
  .preview-content {
    padding: 0;
    box-shadow: none;
  }
  
  .cover-page {
    height: 100vh;
    page-break-after: always;
  }
  
  .toc-page {
    page-break-after: always;
  }
  
  .chapter-page {
    page-break-before: always;
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .preview-container {
    padding: 10px;
  }
  
  .preview-content {
    padding: 20px;
  }
  
  .preview-title-bar {
    flex-direction: column;
    gap: 15px;
    text-align: center;
  }
  
  .cover-title {
    font-size: 28px;
  }
}
</style>